/*
* @Author: steven.wang
* @Date:   2018-12-26 16:35:53
* @Last Modified by:   steven.wang
* @Last Modified time: 2019-03-21 17:11:13
*/
const fs = require("fs");
const superagent = require('superagent');
const cheerio = require('cheerio');
const asyncQuene = require("async").queue;
require('superagent-charset')(superagent);
const query = require('./db');

/**
 * 异步获取页面属性
 * @author   steven.wang
 * @DateTime 2018-12-26T16:05:57+0800
 * @param    {string}                 url 链接
 * @return   {Promise}
 */
const getHtmlAsync = (url, charset = 'gb2312') => {
	return new Promise((resolve, reject) => {
		superagent.get(url)
            .buffer(true)
            .set({'accept-encoding': 'gzip'})
            .charset(charset).then(res => {
			if (res.ok) {
				resolve(cheerio.load(res.text, {decodeEntities: false}))
			} else {
				reject(res.err);
			}
		}, err => {
			reject(err);
		});
	});
}
/**
 * 将画册信息保存为JSON
 * @author steven.wang
 * @DateTime 2019-02-27T11:04:44+0800
 */
const writeJsonToFile = (path, data) => {
	try {
    	fs.writeFileSync(path, JSON.stringify(data));
	} catch(e) {
		// statements
		throw new Error('写入' + path + '失败');
	}
}
/**
 * 国家存储
 * @author steven.wang
 * @DateTime 2019-02-27T11:02:33+0800
 */
const insertCountry = values => {
    return query('insert into country (short_name, zh_name, en_name, phone_code) values ?', [values]);
}
/**
 * 身份存储
 * @author steven.wang
 * @DateTime 2019-03-06T09:22:13+0800
 * @param    {[type]}                 values [description]
 * @return   {[type]}                        [description]
 */
const insertProvince = values => {
    return query('insert into province (name, code, parent_code) values ?', [values]);
}
/**
 * 城市存储
 * @author steven.wang
 * @DateTime 2019-03-06T09:22:28+0800
 */
const insertCity = values => {
    return query('insert into city (name, code, parent_code) values ?', [values]);
}
/**
 * 县/区存储
 * @author steven.wang
 * @DateTime 2019-03-06T09:22:36+0800
 */
const insertCounty = values => {
    return query('insert into county (name, code, parent_code) values ?', [values]);
}
/**
 * 街道存储
 * @author steven.wang
 * @DateTime 2019-03-06T09:22:36+0800
 */
const insertTown = values => {
    return query('insert into town (name, code, parent_code) values ?', [values]);
}
/**
 * 社区存储
 * @author steven.wang
 * @DateTime 2019-03-06T09:22:43+0800
 */
const insertVillage = values => {
    return query('insert into village (name, code, parent_code) values ?', [values]);
}

module.exports = {
	getHtmlAsync,
	writeJsonToFile,
	insertCountry,
    insertProvince,
    insertCity,
    insertCounty,
    insertTown,
    insertVillage
}